package com.lnsf.bookstore.web.book.service.impl;

import com.lnsf.bookstore.web.book.dao.ApiBookMapper;
import com.lnsf.bookstore.web.book.service.ApiBookService;
import com.lnsf.bookstore.web.book.vo.ApiBook;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
public class ApiBookServiceImpl implements ApiBookService {

    @Autowired
    private ApiBookMapper apiBookMapper;

    @Autowired
    private SolrServer solrServer;

    /**
     * 商品信息导入索引库
     * 需要展示给用户的字段、需要搜索的字段需要添加到索引库。
     * 比如商品的id、商品的名称、商品的卖点、商品的价格、商品的图片、商品的分类名称。
     * @return
     */
    @Override
    public Object importItemToIndex() throws IOException, SolrServerException {
        List<ApiBook> apiBookList = apiBookMapper.selectAll();
        //将图书商品列表导入Solr
        for(ApiBook apiBook : apiBookList){
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id", apiBook.getId());
            document.addField("book_pic", apiBook.getPic());
            document.addField("book_price", apiBook.getUnitPrice());
            document.addField("book_category_name", apiBook.getApiCategory().getName());
            //将文档写入索引库
            solrServer.add(document);
        }

        //提交
        solrServer.commit();
        return null;
    }

    @Override
    public List<ApiBook> selectAll(Map<String, Object> map, ApiBook apiBook) {
        return apiBookMapper.selectAll();
    }

    @Override
    public ApiBook queryObject(Integer id) {
        return apiBookMapper.selectByPrimaryKey(id);
    }



    @Override
    public int update(ApiBook apiBook) {
        return apiBookMapper.updateByPrimaryKeySelective(apiBook);
    }

    @Override
    public int save(ApiBook apiBook) {
        return apiBookMapper.insert(apiBook);
    }

    @Override
    public List<ApiBook> queryList(Map<String, Object> map) {
        return apiBookMapper.queryList(map);
    }

    @Override
    public ApiBook checkBook(Map<String, Object> map) {
        return apiBookMapper.checkBook(map);
    }
}
